package com.duan.controller;

import com.duan.base.JSONResponse;
import com.duan.pojo.Member;
import com.duan.pojo.User;
import com.duan.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class MemberController {
    private final MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService){
        this.memberService = memberService;
    }

    //增加
    @PostMapping("/api/member/add")
    public JSONResponse add(@RequestBody Member member, HttpSession session, HttpServletResponse resp){
        User user = (User)session.getAttribute("currentUser");
        JSONResponse jsonResponse = new JSONResponse();

        if(user == null){
            resp.setStatus(401);
            jsonResponse.setSuccess(false);
            jsonResponse.setCode("USR000");
            jsonResponse.setMessage("用户没有登录，不允许访问");

            return jsonResponse;
        }
        int add = memberService.add(member, user.getId());

        jsonResponse.setSuccess(true);
        jsonResponse.setData(member.getId());

        return jsonResponse;
    }

    //修改
    @PostMapping("/api/member/update")
    public JSONResponse update(@RequestBody Member member, HttpSession session, HttpServletResponse resp){
        User user = (User)session.getAttribute("currentUser");
        JSONResponse jsonResponse = new JSONResponse();

        if(user == null){
            resp.setStatus(401);
            jsonResponse.setSuccess(false);
            jsonResponse.setCode("USR000");
            jsonResponse.setMessage("用户没有登录，不允许访问");

            return jsonResponse;
        }
        int n = memberService.update(member);

        jsonResponse.setSuccess(true);

        return jsonResponse;
    }

    //删除
    @GetMapping("/api/member/delete/{memberId}")
    public JSONResponse delete(@PathVariable Integer memberId, HttpSession session, HttpServletResponse resp){
        User user = (User)session.getAttribute("currentUser");
        JSONResponse jsonResponse = new JSONResponse();

        if(user == null){
            resp.setStatus(401);
            jsonResponse.setSuccess(false);
            jsonResponse.setCode("USR000");
            jsonResponse.setMessage("用户没有登录，不允许访问");

            return jsonResponse;
        }

        int n = memberService.delete(memberId);
        jsonResponse.setSuccess(true);

        return jsonResponse;
    }

}
